#include "Texture.h"
#include "sdl_gltexture.h"

#include <SDL.h>
#include <SDL_image.h>

namespace Lame3d
{
	Texture::Texture(const File &f)
			: refCount(0), glTexture(0), file(f)
	{
	}
	
	Texture::~Texture()
	{
		if(refCount > 0) {
			throw "Destructing texture with nonzero refcount.";
		}
	}
	
	Texture::Handle Texture::GetHandle()
	{
		if(refCount == 0) {
			load();
		}
		return Handle(*this);
	}
	
	void Texture::load()
	{
		printf("loading texture %s\n...", file.GetPath().c_str());
		SDL_Surface *imgSurface;
		if((imgSurface = IMG_Load(file.GetPath().c_str())) == NULL) {
			throw "Failed to load image as texture.";
		}
		glTexture = SDL_GL_LoadTexture(imgSurface);
		SDL_FreeSurface(imgSurface);
	}
	
	void Texture::unload()
	{
		printf("unloading texture %s\n...", file.GetPath().c_str());
		glDeleteTextures(1, &glTexture);
	}
	
	// Texture::Handle
	Texture::Handle::Handle(Texture &t)
			: texture(&t)
	{
		texture->refCount++;
	}
	
	Texture::Handle::~Handle()
	{
		texture->refCount--;
		if(texture->refCount < 1) {
			texture->unload();
		}
	}
	
	void Texture::Handle::Bind2d()
	{
		glBindTexture(GL_TEXTURE_2D, texture->glTexture);
	}
	
	void Texture::Handle::Coord(float u, float v)
	{
		glTexCoord2f(u, v);
	}
	
	GLuint Texture::Handle::GlTexture()
	{
		return texture->glTexture;
	}
	
	Texture::Handle& Texture::Handle::operator=(const Handle &h)
	{
		texture->refCount--;
		if(texture->refCount < 1) {
			texture->unload();
		}
		texture = h.texture;
		texture->refCount++;
		return *this;
	}
}

// eof
